//
//  HBComposeView.swift
//  sinaWeibo
//
//  Created by Beans on 16/6/29.
//  Copyright © 2016年 iceWorks. All rights reserved.
//

import UIKit

// 枚举, 动画方向
enum ComposeAnimationType: Int {
    case Up = 0
    case Down = 1
    case Left = 2
    case Right = 3
}

class HBComposeView: UIView {

    // (1)定义成员变量vc, 接收控制器
    var viewController: UIViewController?

    // 定义数组, 盛放按钮
    private lazy var composeBtns: [UIButton] = [UIButton]()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        backgroundColor = UIColor.yellowColor()
        var frame = self.frame
        frame.size = kScreenSize
        self.frame = frame

        addSubview(bgImageView)

        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self)
        }

        addButtons()
    }

    // 添加按钮
    private func addButtons() {
        // 0> 设置固定值
        let colCount = 3
        let childBtnW: CGFloat = 80
        let childBtnH: CGFloat = 110
        let childBtnMargin = (kScreenWidth - childBtnW * CGFloat(colCount)) / (CGFloat(colCount) + 1)
        // 1> 读取plist文件
        let composeArr = NSArray(contentsOfFile: NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!)!
        // 2> 遍历数组
        for i in 0..<composeArr.count {
            // 3> 实例化对象
            let btn = HBComposeButton()

            // 4> 设置数据
            let imgStr = composeArr[i]["icon"] as! String   // `as!`, 只要敢保证前面的数据有值且类型正确
            let title = composeArr[i]["title"] as! String
            btn.setImage(UIImage(named: imgStr), forState: .Normal)
            btn.setTitle(title, forState: .Normal)

            // 5> 设置frame
            btn.frame.size = CGSizeMake(childBtnW, childBtnH)
            let col = i % colCount
            let row = i / colCount
            btn.frame.origin.x = childBtnMargin * (CGFloat(col) + 1) + childBtnW * CGFloat(col)
            btn.frame.origin.y = childBtnMargin * CGFloat(row) + childBtnH * CGFloat(row) + 250

            btn.addTarget(self, action: "buttonClick:", forControlEvents: .TouchUpInside)
            addSubview(btn)
            composeBtns.append(btn)
        }
    }

    // MARK: - 添加动画的方法
    private func addButtonAnimation(button: UIButton, time: CFTimeInterval, type: ComposeAnimationType) {
        // 创建springAnim
        // 修改toValue
        if type == .Up {          // 向上

        } else if type == .Down {   // 向下

        }
        // 弹性反弹
        // 设置springSpeed
        // 开始时间
        // 添加动画
    }

    // 对象方法
    private func showAnimation(targetVC: UIViewController) {
        // (2)对象传值 -- 传控制器(tabBarVc)
        viewController = targetVC
        viewController?.view.addSubview(self)

        // 遍历数组添加动画
        for (index, btn) in composeBtns.enumerate() {
            addButtonAnimation(btn, time: CACurrentMediaTime() + 0.025 * Double(index), type: .Up)
        }
    }

    // 类方法, 方便外接调用
    class func showAnimation(targetVC: UIViewController) {
//        self.showAnimation(targetVC)          // tabBarVc调用方法时出错 warning: could not load any Objective-C class information. This will significantly reduce the quality of type information available.
        HBComposeView().showAnimation(targetVC)
    }

    // MARK: - 实现touch方法
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
         printLog("touch began")
        // 为什么直接remove没有看到任何效果, 因为动画还没有来得及执行

        // 根据动画效果, 是反着的. 反向遍历数组
        for (index, btn) in composeBtns.reverse().enumerate() {
            addButtonAnimation(btn, time: CACurrentMediaTime() + 0.025 * Double(index), type: .Down)
        }

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.removeFromSuperview()
        }

    }

    // MARK: - 按钮的点击方法
    @objc private func buttonClick(button: UIButton) {

        UIView.animateWithDuration(0.25, animations: { () -> Void in
            for obj in self.composeBtns {
                obj.alpha = 0
                if obj == button {
                    obj.transform = CGAffineTransformMakeScale(2.0, 2.0)
                } else {
                    obj.transform = CGAffineTransformMakeScale(0.3, 0.3)
                }
            }

            }) { (_) -> Void in
                // (3)动画完成后进行页面跳转 {通知/代理/闭包, 这里采用对象传值}
                let nav = UINavigationController(rootViewController: HBPublishViewController())
                self.viewController?.presentViewController(nav, animated: true, completion: { () -> Void in
                })
        }
    }

    // lazy load
    private lazy var bgImageView: UIImageView = {
        // 获取当前屏幕的截图
        let imgV = UIImageView(image: UIImage.getScreenShot())

        // 创建毛玻璃视图 (iOS8之后)
        let effect = UIBlurEffect(style: UIBlurEffectStyle.Light)
        let effectView = UIVisualEffectView(effect: effect)
        // 添加毛玻璃
        imgV.addSubview(effectView)
        // 毛玻璃约束
        effectView.snp_makeConstraints(closure: { (make) -> Void in
            make.edges.equalTo(imgV)
        })

        return imgV
    }()
}
